﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Xugege.AbpExtension.Application.Extension.File.Dto;
using Xugege.AbpExtension.Core.Extension.File;

namespace Xugege.AbpExtension.Application.Extension.File
{
    public class FileAppService : AbpZeroTemplateAppServiceBase, IFileAppService
    {

        private readonly IAppFolderExtension _appFolderExtension;
        private readonly IRepository<UploadFileRecord, long> _uploadFileRepository;

        public FileAppService(IAppFolderExtension appFolderExtension,
            IRepository<UploadFileRecord, long> uploadFileRepository)
        {
            _appFolderExtension = appFolderExtension;
            _uploadFileRepository = uploadFileRepository;
        }

        /// <summary>
        /// 根据文件guid获取文件相对路径（获取上传文件相对路径）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<NameValue<string>> GetFilePath(GetFilePathInputDto input)
        {
            NameValue<string> result = new NameValue();
            if (!input.FileId.HasValue) return result;
            var file = await _uploadFileRepository.FirstOrDefaultAsync(m => m.InstanceId == input.FileId.Value);
            if (file == null) return result;
            return new NameValue(input.FileId.ToString(), file.RealPath);
        }

        public async Task<IList<NameValue<string>>> GetFilePaths(GetFilePathInputDto input)
        {
            var fileIds = input.FileIds.IsNullOrEmpty() ? new List<Guid>() : input.FileIds.Split(';').Select(m =>
               {
                   var g = Guid.Empty;
                   Guid.TryParse(m, out g);
                   return g;
               }).ToList();
            var files = await _uploadFileRepository.GetAll().Where(m => fileIds.Contains(m.InstanceId)).ToListAsync();
            return files.Select(m => new NameValue<string>(m.InstanceId.ToString(), m.RealPath)).ToList();
        }
    }
}
